import { Toast } from 'mint-ui'
import * as ThreeStorage from '@/utils/store/token.js' // cookie local session 统一管理
import * as AccountApi from '@/api/account'
import router from '@/router/index'
import Store from '@/store/index'
const AppId = process.env.WX_APP_ID // 微信公众号appid
const RedirectUrl = process.env.WX_CALLBACK_SAFE_URL // 微信公众号设置的安全回调域名
import { isWechat } from '@/utils/isJudge'

console.log(' vuex -state 初始化-此处getoken()是初始化取token')
const account = {
  state: {
    token: ThreeStorage.getToken(),
    refreshToken: ThreeStorage.getRefreshToken(),
    name: '',
    userInfo: '',
    DriverId: ThreeStorage.getDriverId(),
    loadingShow: false,
    wxcode: ThreeStorage.getWxCode(),
    loginStamp: ThreeStorage.getLoginStamp(),
    userKey: ThreeStorage.getUserkey(), // userkey 登录账号
    accountId: ThreeStorage.getAccountId(), // 账号标示
    tenantId: ThreeStorage.getTenantId(), // 管理员（公司）标示
    loginType: ThreeStorage.getLoginType(),
    carInfo: ThreeStorage.getCarInfo(), // 当前车队信息
    allCarInfo: ThreeStorage.getAllCarInfo()// 所有车队信息
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
      ThreeStorage.setToken(token) // 注：设置token
      // console.log('SET_TOKEN-cookie', cookieApi.get('ssoToken'))
    },
    SET_REFRESH_TOKEN: (state, token) => {
      state.refreshToken = token
      ThreeStorage.setRefreshToken(token)
    },
    SET_NAME: (state, name) => {
      state.name = name
    },
    SET_ENTITYNAME: (state, entityName) => {
      state.entityName = entityName
    },
    SET_USERIFRO: (state, userInfo) => {
      state.userInfo = userInfo
    },
    SET_TENANT_ID: (state, TenantId) => {
      state.TenantId = TenantId
      ThreeStorage.setTenantId(TenantId)
    },
    SET_DRIVER_ID: (state, DriverId) => {
      state.DriverId = DriverId
      ThreeStorage.setDriverId(DriverId)
    },
    SET_LOADING_SHOW: (state, loadingShow) => {
      state.loadingShow = loadingShow
    },
    SET_WX_CODE: (state, wxcode) => {
      // 因为wxcode 是5分钟失效 需要重新请求
      console.log('store-wxcode', wxcode)
      state.wxcode = wxcode
      ThreeStorage.setWxCode(wxcode)
    },
    SET_TOKEN_STAMP: (state, nowTimeStamp) => {
      // const nowTimeStamp = Date.parse(new Date()) // 当前时间戳
      state.loginStamp = nowTimeStamp
      ThreeStorage.setLoginStamp(nowTimeStamp)
    },
    SET_LOGIN_TYPE: (state, loginType) => {
      state.loginType = loginType
      ThreeStorage.setLoginType(loginType)
    },
    SET_USERKEY: (state, userkey) => {
      state.userkey = userkey
      ThreeStorage.setUserkey(userkey)
    },
    SET_ACCOUNT_ID: (state, accountId) => {
      state.accountId = accountId
      ThreeStorage.setAccountId(accountId)
    },
    SET_CAR_INFO: (state, carInfo) => {
      state.carInfo = carInfo
      ThreeStorage.setCarInfo(carInfo)
    },
    SET_ALL_CAR_INFO: (state, allCarInfo) => {
      state.allCarInfo = allCarInfo
      ThreeStorage.setAllCarInfo(allCarInfo)
    }
  },

  actions: {
    // 账号密码登录 ,竞价共用
    Login({ commit }, userInfo) {
      // console.log('action-login()-userInfo', userInfo)
      const userKey = userInfo.username
      const userVal = userInfo.password
      return new Promise((resolve, reject) => {
        commit('SET_LOADING_SHOW', true)
        const formData = new FormData()
        formData.append('username', userKey)
        formData.append('password', userVal)
        formData.append('grant_type', 'password')
        formData.append('client_id', 'devops')
        formData.append('client_secret', 'devops')
        AccountApi.getSsoToken(formData).then(res => {
          if (res.status === 200) {
            commit('SET_LOADING_SHOW', false)
            const token = res.data.access_token
            console.log(res)
            if (!token) {
              Toast({
                message: '账号或密码错误!',
                duration: 1000
              })
              return
            }
            const refreshToken = res.data.refresh_token
            const nowTimeStamp = res.data.gmt_create
            const account_id = res.data.accountId
            const tenant_id = res.data.tenantId
            commit('SET_TOKEN', token)
            commit('SET_ACCOUNT_ID', account_id)
            commit('SET_TENANT_ID', tenant_id)
            commit('SET_USERKEY', userKey)
            commit('SET_TOKEN_STAMP', nowTimeStamp) // 存储登录时的时间戳 用于判断 token 2小时后失效
            commit('SET_REFRESH_TOKEN', refreshToken) // 存储  refreshToken 用于token2小时失效后的重新登陆，存储local即可

            const roles_val = res.data.roles[0].authority
            // 走竞价平台
            if (ThreeStorage.getRolesVal()) {
              AccountApi.getCarInfo(userKey).then(res => {
                console.log('------------------车队信息', res)
                commit('SET_LOADING_SHOW', false)
                if (res.code === 0 && res.data.role === 'fleet') {
                  if (res.data.fleets.length > 0) {
                    // 当前车队信息
                    const carInfo = {
                      currentFleetId: res.data.fleets[0] && res.data.fleets[0].id,
                      fleetName: res.data.fleets[0] && res.data.fleets[0].fleetName,
                      phone: res.data.mobile
                    }
                    // 所有车队信息--数组要转成对象
                    const allCarInfo = {
                      allCarInfo: res.data.fleets
                    }
                    commit('SET_CAR_INFO', carInfo)
                    commit('SET_ALL_CAR_INFO', allCarInfo)
                    Toast({
                      message: '登录成功',
                      duration: 1000
                    })
                    // 竞价平台也要初始化路由权限列表，因为和运力共用
                    const loginType = 'company'
                    commit('SET_LOGIN_TYPE', loginType)
                    Store.dispatch('InitRouter')
                    // 是微信端登录就获取微信code，否则直接登录
                    if (isWechat()) {
                      Store.dispatch('wxAuthorize')
                    } else {
                      router.push({ name: 'bid-home' })
                    }
                  } else {
                    Toast({
                      message: '此账号未绑定车队',
                      duration: 1000
                    })
                    return
                  }
                } else {
                  Toast({
                    message: '非车队人员无权限登录',
                    duration: 1000
                  })
                  return
                }
                resolve()
              }).catch(error => {
                commit('SET_LOADING_SHOW', false)
                Toast({
                  message: error.message,
                  duration: 1000
                })
                reject(error)
              })
            } else {
              // 走运力平台
              let loginType = ''
              if (roles_val === 'ROLE_ADMIN') {
                loginType = 'company'
                commit('SET_LOGIN_TYPE', loginType)
                Toast({
                  message: '登录成功',
                  duration: 1000
                })
                Store.dispatch('InitRouter')
                router.push({ name: 'me-adminLanding' })
              } else if (roles_val === 'ROLE_NORMAL') {
                loginType = 'driver'
                commit('SET_LOGIN_TYPE', loginType)
                AccountApi.getLogin(userKey).then(res => {
                  // console.log('getLogin', res, 'res.data.id', res.data.id)
                  commit('SET_LOADING_SHOW', false)
                  if (res.code === 0) {
                    Toast({
                      message: '登录成功',
                      duration: 1000
                    })
                    Store.dispatch('InitRouter')
                    commit('SET_DRIVER_ID', res.data.id)
                    router.push({ name: 'me-driverLanding' })
                  }
                  resolve()
                }).catch(res => {
                  commit('SET_LOADING_SHOW', false)
                  console.warn('error', res)
                })
              }
            }
          }
        }).catch(error => {
          commit('SET_LOADING_SHOW', false)
          Toast({
            message: error.message,
            duration: 1000
          })
          console.log('error', error)
          reject(error)
        })
      })
    },
    // 短信验证码登录
    LoginSms({ commit }, userInfo) {
      // console.log('store-login', userInfo)
      const userKey = userInfo.username
      const userVal = userInfo.verifyCode
      return new Promise((resolve, reject) => {
        commit('SET_LOADING_SHOW', true)
        const formData = new FormData()
        formData.append('username', userKey)
        formData.append('password', userVal)
        formData.append('grant_type', 'password')
        formData.append('client_id', 'devops')
        formData.append('client_secret', 'devops')
        formData.append('auth_type', 'sms')
        // formData.append('sms_code', userVal)
        AccountApi.getSsoToken(formData).then(res => {
          // console.log('getSsoToken', res)
          commit('SET_LOADING_SHOW', false)
          if (res.status === 200) {
            const token = res.data.access_token
            if (!token) {
              Toast({
                message: '账号或密码错误!',
                duration: 1000
              })
              return
            }
            const refreshToken = res.data.refresh_token
            const nowTimeStamp = res.data.gmt_create
            // const res_roule = res.data.roules
            const account_id = res.data.accountId
            const tenant_id = res.data.tenantId
            commit('SET_TOKEN', token)
            commit('SET_ACCOUNT_ID', account_id)
            commit('SET_TENANT_ID', tenant_id)
            commit('SET_USERKEY', userKey)
            commit('SET_TOKEN_STAMP', nowTimeStamp)
            commit('SET_REFRESH_TOKEN', refreshToken)
            const roles_list0 = res.data.roles[0]
            const roles_val = roles_list0.authority
            let loginType = ''
            if (roles_val === 'ROLE_ADMIN') {
              loginType = 'company'
              Toast({
                message: '登录成功',
                duration: 1000
              })
              commit('SET_LOGIN_TYPE', loginType)
              router.push({ name: 'me-adminLanding' })
            } else if (roles_val === 'ROLE_NORMAL') {
              loginType = 'driver'
              commit('SET_LOGIN_TYPE', loginType)
              AccountApi.getLogin(userKey).then(res => {
                // console.log('getLogin', res, 'res.data.id', res.data.id)
                commit('SET_LOADING_SHOW', false)
                if (res.code === 0) {
                  Toast({
                    message: '登录成功',
                    duration: 1000
                  })
                  commit('SET_DRIVER_ID', res.data.id)
                  router.push({ name: 'me-driverLanding' })
                }
                resolve()
              }).catch(res => {
                commit('SET_LOADING_SHOW', false)
                console.warn('error', res)
              })
            }
            console.log('roles_val', roles_val, 'loginType', loginType)
          }
        }).catch(error => {
          commit('SET_LOADING_SHOW', false)
          console.log('error', error)
          reject(error)
        })
      })
    },
    // 重新登陆
    LoginRefresh({ commit }) {
      const local_refresh_token = ThreeStorage.getRefreshToken()
      const userKey = ThreeStorage.getUserkey()
      console.log('LoginRefresh()-local_refresh_token', 'USER_KEY', userKey)
      return new Promise((resolve, reject) => {
        commit('SET_LOADING_SHOW', true)
        const formData = new FormData()
        formData.append('grant_type', 'refresh_token')
        formData.append('client_id', 'devops')
        formData.append('client_secret', 'devops')
        formData.append('refresh_token', local_refresh_token)
        AccountApi.getSsoToken(formData).then(res => {
          // console.log('getSsoToken', res)
          commit('SET_LOADING_SHOW', false)
          if (res.status === 200) {
            const token = res.data.access_token
            if (!token) {
              Toast({
                message: '请重新登录!',
                duration: 1000
              })
              Store.dispatch('FedLogOut')
            }
            const refreshToken = res.data.refresh_token
            const nowTimeStamp = res.data.gmt_create
            const account_id = res.data.accountId
            const tenant_id = res.data.tenantId
            commit('SET_TOKEN', token)
            commit('SET_ACCOUNT_ID', account_id)
            commit('SET_TENANT_ID', tenant_id)
            commit('SET_TOKEN_STAMP', nowTimeStamp)
            commit('SET_USERKEY', userKey)
            commit('SET_REFRESH_TOKEN', refreshToken)
            const roles_list0 = res.data.roles[0]
            const roles_val = roles_list0.authority

            let loginType = ''
            // 竞价平台也要初始化路由权限列表，因为和运力共用
            if (ThreeStorage.getRolesVal()) {
              loginType = 'company'
              commit('SET_LOGIN_TYPE', loginType)
            } else {
              if (roles_val === 'ROLE_ADMIN') {
                loginType = 'company'
                commit('SET_LOGIN_TYPE', loginType)
              } else if (roles_val === 'ROLE_NORMAL') {
                loginType = 'driver'
                commit('SET_LOGIN_TYPE', loginType)
              } else {
                this.FedLogOut()
              }
            }
            AccountApi.getLogin(userKey).then(res => {
              // console.log('getLogin', res, 'res.data.id', res.data.id, '')
              commit('SET_LOADING_SHOW', false)
              if (res.code === 0) {
                Toast({
                  message: '重新登录成功',
                  duration: 1000
                })
                Store.dispatch('InitRouter')
                if (ThreeStorage.getRolesVal()) {
                  location.reload()
                  router.push({ name: 'bid-home' })
                } else {
                  if (loginType === 'driver') {
                    // 司机api  id 为  DRIVER_ID
                    commit('SET_DRIVER_ID', res.data.id)
                    location.reload()
                    router.push({ name: 'driver-home' })
                    // router.go(0) // 刷新相同路由页面数据
                  } else if (loginType === 'company') {
                    location.reload()
                    router.push({ name: 'admin-home' })
                  }
                }
              } else {
                Toast({
                  message: res.message || '请重新登录',
                  duration: 1000
                })
                Store.dispatch('FedLogOut')
                return
                // 如果登录失败，
              }
              resolve()
            }).catch(res => {
              commit('SET_LOADING_SHOW', false)
              Store.dispatch('FedLogOut')
              // console.log('getLogin', res)
            })
          }
        }).catch(error => {
          commit('SET_LOADING_SHOW', false)
          // console.warn('error', error)
          Store.dispatch('FedLogOut')
          reject(error)
          this.FedLogOut()
        })
      })
    },
    // 免费注册
    Register({ commit }) {
      return new Promise((resole, reject) => {
        console.log('Register', resole, reject)
        // const register = '123'
        // ThreeStorage.setToken(register)
        // commit('SET_TOKEN', register)
        resole()
      })
    },

    // 获取用户信息
    GetInfo({ commit, state }) {
      return new Promise((resolve, reject) => {
        AccountApi.getAccountInfo().then(response => {
          const data = response.data
          console.log('获取用户信息getAccountInfo+InitRouter', data)
          // Store.dispatch('InitRouter')
          resolve(response)
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 前端 登出
    FedLogOut({ commit }) {
      return new Promise(resolve => {
        ThreeStorage.cleanToken() // cookie-token local-refreshToken session-token
        ThreeStorage.cleanLoginStamp()
        ThreeStorage.cleanWxCode()
        ThreeStorage.cleanUserkey()
        ThreeStorage.cleanDriverId()
        ThreeStorage.cleanLoginType()
        ThreeStorage.cleanRouterList()
        ThreeStorage.cleanAccountId()
        ThreeStorage.cleanCarInfo()
        ThreeStorage.cleanAllCarInfo()
        ThreeStorage.cleanDealListInfo()
        /* roles_val保存在sessionStorage中，点击退出登录是返回登录界面，
				无需清掉此字段,退出公众号会自动清掉*/
        // ThreeStorage.cleanRolesVal()
        console.log('前端登出')
        router.push({ name: 'signup-normal' })
      })
    },

    // 用户微信授权
    wxAuthorize({ commit }) {
      console.log('进行用户微信授权阶段' + '-------------------+++++++++++++++')
      return new Promise(resolve => {
        const URL = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' + AppId +
			  '&redirect_uri=' + encodeURIComponent(RedirectUrl + '/bid/bidHome') + '&response_type=code&scope=snsapi_base&state=STATE&connect_redirect=1#wechat_redirect'
        window.location.href = URL
			  // window.location.href = "http://localhost:8080/bid/bidHome?code='xxxxxxx11'"
      })
    }
  }
}

export default account
